﻿Imports Microsoft.Xna.Framework

Namespace Global.Runa.UI.Animation

    Public Class FloatAnimation
        Inherits AnimationBase

        Public From As Nullable(Of Single) = 0.0!
        Public [To] As Single = 0.0!

        Private Incremental As Single = 0.0!
        Private Value As Single

        Public Sub New()
            MyBase.New()
        End Sub

        Public Sub New(ByVal fps As Single)
            MyBase.New(fps)
        End Sub

        Public Overrides Sub BeginAnimation(ByVal Control As IAnimatable, ByVal TargetPropertyName As String)
            If Not Control.Animations.Contains(Me) Then
                MyBase.BeginAnimation(Control, TargetPropertyName)
                If Not Me.From.HasValue Then
                    Me.From = New Nullable(Of Single)(CSng(MyBase.TargetProperty.GetValue(Control, Nothing)))
                End If
                Me.Incremental = Me.CalculateIncremental(Me.From.Value, Me.To, MyBase.Duration)
                Me.Value = Me.From.Value
            End If
        End Sub

        Private Function CalculateIncremental(ByVal Orgion As Single, ByVal [End] As Single, ByVal Time As TimeSpan) As Single
            Dim TotalFrames As Integer = CInt(Time.TotalSeconds * Me.FPS)
            Dim inc = ([End] - Orgion) / CSng(TotalFrames)
            'Return Math.Truncate(inc * 1000) / 1000.0
            Return inc
        End Function

        Public Overrides Sub OnComplete()
            MyBase.TargetProperty.SetValue(MyBase.TargetObject, Me.To, Nothing)
            MyBase.OnComplete()
        End Sub

        Public Overrides Sub Updata(ByVal gameTime As GameTime)
            If MyBase.IsEnabled Then
                If Not MyBase.EasingFunction Is Nothing Then
                    Me.Incremental = CSng(MyBase.EasingFunction.GetIncremental(Me.Incremental, MyBase.Progress, MyBase.Duration))
                End If
                If Math.Abs(Me.To - Me.Value) >= Math.Abs(Me.Incremental * MyBase.Coefficient) Then
                    Me.Value += Me.Incremental * MyBase.Coefficient
                    MyBase.TargetProperty.SetValue(MyBase.TargetObject, Me.Value, Nothing)
                End If
                MyBase.Updata(gameTime)
            End If
        End Sub

    End Class

End Namespace